package com.woniu.controller;

import com.woniu.domain.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Api(tags = "sssssssssssssssuser表增删改查")
@Slf4j
@RestController
@RequestMapping("user")
@EnableEurekaClient
@MapperScan(basePackages = "com.woniu.mapper")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    private static final String URL = "http://localhost:9000/user/";


    @Autowired
    private DiscoveryClient discoveryClient;


    @ApiOperation("查询所有user")
    @GetMapping
    public List<User> selectAllUser(){
        String url = URL ;

        List forObject = restTemplate.getForObject(url, List.class);
        return forObject;
    }

    @ApiOperation("查询所有useraa")
    @GetMapping("/get")
    public List<User> selectAllUserPl(){

        List<ServiceInstance> instances = discoveryClient.getInstances("CINEMA-MEMBER");
        ServiceInstance serviceInstance = instances.get(0);
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();




      //  String url = "http://"+host+":"+port+"/user" ;
        String url = "http://CINEMA-MEMBER/user";
        List forObject = restTemplate.getForObject(url, List.class);
        return forObject;
    }

    @ApiOperation("根据id修改user")
    @PutMapping
    String updateUserById(@RequestBody User user){
        String url = URL ;
        restTemplate.put(url,user);

        log.info("修改成功");

        return "success";
    }

    @ApiOperation("添加一个user")
    @PostMapping
    String insertUser(@RequestBody User user){
        String url = URL ;
        restTemplate.postForObject(url,user,String.class);

        log.info("增加成功");

        return "success";
    }

    @ApiOperation("根据id删除一个user")
    @DeleteMapping("{id}")
    void deleteUserById(@PathVariable Integer id){

        String url = URL +id;

        restTemplate.delete(url);

    }

}
